package com.hitrust.gs.integration.socket;

import java.net.*;

import com.hitrust.gs.lib.GSSystemConfigurator;

public class SocketUtil 
{
	/**
	 * Logger for this class
	 */
	private static final int BUF_SIZE = 1024*10 ;
	
	public static String receive(Socket socket,String charSet,String caller) throws Exception
	{
		socket.setSoTimeout(60*1000);//设置60秒超时

		byte buf[] = new byte[BUF_SIZE];
		int len = socket.getInputStream().read(buf);
        if(len == -1)
            return "";
		String ret = new String(buf,0,len,charSet);

		return ret ;
	}

	//接受返回信息
	 public static void send(Socket socket,String s,String charSet,String caller) throws Exception
	 {
         socket.setSoTimeout(60*1000);//设置60秒超时

		 socket.getOutputStream().write(s.getBytes(charSet));
		 socket.getOutputStream().flush();

	 }
	 
	 //测试接口
	 public static boolean testSelfSocket()
	 {
	 	boolean isTestOk = false;
	 	String strReturn = "";
		Socket testSocket = null;
	 	try{
			String tPort = GSSystemConfigurator.getParam("gs.server.port");
			//请求建立连接					  
			testSocket = new Socket("127.0.0.1",Integer.parseInt(tPort));			
			send(testSocket,new String(GSServerThread.TESTING_COMMAND.getBytes("GB2312")),"utf-8","");
			strReturn = receive(testSocket,"utf-8","");
			if (strReturn.equals(GSServerThread.TESTING_OK))
			{
				isTestOk = true;
			}
			
	 	}catch (Exception e)
	 	{
	 		
	 	}finally{
			try{
				if(testSocket != null){
					testSocket.close();
				}
			}catch(Exception e){		   
			}
		}
	 	
	 	return isTestOk;
	 }
	
}
